'use strict'
process.chdir(__dirname)
const titbit = require('titbit')
const fs = require('fs')
const pg = require('pg');
const {httpcli} = require('gohttp')   //使用HTTP/1.1的客户端
const wxkey = require('./wxkey.js')
const tbloader = require('titbit-loader')

const dbconfig = require('./dbconfig.js')
//初始化数据连接 
let psql = new pg.Pool(dbconfig)


const token = require('titbit-token')

let tok = new token({
    expires:30,
    key:'20010614200106142001061420010614',  //必须是32位
    iv:'tianyuxuan010614'  //必须是16位
})


try{
    fs.accessSync('./images')
}catch(err){
    fs.mkdirSync('./images')
}

let cert_path = '/usr/local/share'

const app = new titbit({
    //开启模式调试，会输出错误信息
    debug:true,
    cert:`${cert_path}/api.qasdwer.xyz.pem`,
    key:`${cert_path}/api.qasdwer.xyz.key`
})

//一定在初始化qpp之后
let tb = new tbloader();
tb.init(app);


//就是在app.service对象上添加了一个属性
app.addService('tok',tok);
app.addService('psql',psql);
app.addService('imagePath',`${__dirname}/images`)


//c就是context
app.get('/',async c => {
    c.send('ok');
})

app.get('/upload',async c => {
    //c.helper是助手函数模块，其中有对stream.pipe的封装
    //c.reply是响应对象，http/1.1中指向response,http/2中指向stream
    await c.helper.pipe('./upload.html',c.reply)
})

//括号开头 加分号
// ;(async () => {

// })();



//:代表参数的路由，是动态路由  /image/a.jpg  只能是两层路径

app.get('/user/:name/:age/:mobile',async c => {
    console.log(c.param)
    c.send(c.param)
})//结果：{"name":"tian","age":"20","mobile":"liu"}


app.get('mp-login/:code',async c=>{
    c.send(c.param)
    let auth_ul = `https://api.weixin.qq.com/sns/jscode2session`
    +`?appid=${wxkey.appid}`
    +`&secret=${wxkey.secret}`
    +`&js_code=${c.param.code}`
    +`&grant_type=authorization_code`

    let ret = await httpcli.get(auth_ul)
                            .then(res => {
                                return res.json() //返回文本
                            })

    c.send(tok.make(ret))
})

//监听1234端口运行服务。
app.run(2020);